<template>
  <div class="dashboard-container">
    <div class="container">
      <div class="tableBar">
        <!-- 用户的表单信息 -->
        <label style="margin-right: 5px">用户姓名:</label>
        <el-input v-model="username" placeholder="请输入用户姓名" style="width: 15%" @blur="pageQuery()" />
        <el-button type="primary" style="margin-left: 25px" @click="pageQuery()">查询</el-button>
        <el-button type="primary" style="float: right" @click="handleAddUser">+添加用户</el-button>
      </div>
      <el-table v-if="tableData.length" :data="tableData" class="tableBox" stripe>
        <el-table-column type="index" label="编号"></el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="image" label="图片">
          <template slot-scope="{ row }">
            <el-image
              style="width: 20%; height: auto; border: none; cursor: pointer"
              :src="row.image"
            >
              <div slot="error" class="image-slot">
                <img
                  src="../assets/images/user.png"
                  style="width: auto; height: 40px; border: none"
                />
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="sex" label="性别"></el-table-column>
        <el-table-column prop="phone" label="手机号"></el-table-column>

        <el-table-column prop="status" label="身份">
          <template slot-scope="{ row }">
            <span>{{ row.status===1?'管理员':row.status===2?'项目负责人':'成员' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="handleUpdateUser(scope.row)">修改</el-button>
            <el-button type="text" @click="deleteUser(scope.row)">删除</el-button>
            <el-button type="text" @click="authorization(scope.row)">授权</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 授权对话框 -->
      <el-dialog title="授权" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
        <el-select v-model="value" placeholder="请选择要赋予的权限" @change="handleSelectChange">
          <el-option v-for="item in authors" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="rightAuth">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分页 -->
      <el-pagination
        class="pageList"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[10, 20, 30, 40, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import Cookies from "js-cookie";
import {
  getUserList,
  deleteUserById,
  authorization,
  getAuth
} from "@/api/login-register";
export default {
  name: "User",
  data() {
    return {
      username: "",
      page: 1, //页码
      pageSize: 10, //每页记录数
      total: 0, //总记录数
      //当前页要展示的数据集合
      tableData: [],
      dialogVisible: false,
      authors: [],
      value: "",
      userId: ""
    };
  },

  mounted() {},
  created() {
    this.pageQuery();
    // 查询权限列表
    this.selectAuthors();
  },
  methods: {
    rightAuth() {
      const value = this.value;
      authorization(this.userId, value).then(
        res => {
          if (res.data.code === 200) {
            // 授权成功
            this.$message.success("授权成功");
            this.pageQuery();
            // 关闭弹框
            this.dialogVisible = false;
          } else {
            alert(res.data.message);
          }
        },
        err => {
          alert(err.$message);
        }
      );
    },
    handleSelectChange(value) {
      console.log("选择的权限 ID:", value);
      this.value = value;
      alert(typeof(this.value))
    },
    selectAuthors() {
      getAuth().then(
        res => {
          if (res.data.code === 200) {
            this.authors = res.data.data;
            console.log("authors", this.authors);
          } else {
            alert(res.data.message);
          }
        },
        err => {
          alert(err.message);
        }
      );
    },

    //分页查询
    pageQuery() {
      //准备请求参数
      const params = {
        username: this.username,
        page: this.page,
        pageSize: this.pageSize
      };

      //发送Ajax请求，访问后端服务，获取分页数据
      getUserList(params)
        .then(res => {
          if (res.data.code === 200) {
            this.total = res.data.data.total;
            this.tableData = res.data.data.records;
          }
        })
        .catch(err => {
          this.$message.error("请求出错了：" + err.message);
        });
    },
    //pageSize发生变化时触发
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.pageQuery();
    },
    //page发生变化时触发
    handleCurrentChange(page) {
      this.page = page;
      this.pageQuery();
    },
    handleAddUser() {
      this.$router.push({
        path: "/layout/addUser"
      });
    },
    handleUpdateUser(row) {
      if (row.status === 1) {
        console.log("row.status", row.status);
        this.$message.error("管理员账号，不能修改！");
        return;
      }

      //跳转到修改页面，通过地址栏传递参数
      this.$router.push({
        path: "/layout/addUser",
        query: { id: row.id }
      });
    },
    deleteUser(row) {
      console.log("row.status", row.status);
      if (row.status === 1) {
        this.$message.error("管理员账号，不能删除！");
        return;
      }
      //弹出确认提示框
      this.$confirm("确认要删除当前用户吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          const p = {
            id: row.id
          };
          // 删除接口
          deleteUserById(p).then(res => {
            if (res.data.code === 200) {
              this.$message.success("用户删除成功！");
              this.pageQuery();
            }else{
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(e => e);
    },
    handleAvatarSuccess(res, file) {
      // 图片上传成功修改头像
      Cookies.set("imageUrl", res.data);
      this.$store.commit("setImage", res.data);
      this.form.image = res.data;
    },
    authorization(row) {
      this.dialogVisible = true;
      this.userId = row.id;
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          done();
        })
        .catch(_ => {});
    }
  },

  computed: {
    showImage() {
      return Cookies.get("imageUrl");
    }
  }
};
</script>


<style lang="less" scoped>
.disabled-text {
  color: #bac0cd !important;
}
.dashboard-container {
  .container {
    .tableBox {
      margin-top: 10px;
      width: 100%;
      border: 1px solid #c3c8ce;
      border-bottom: 0;
      .createTime {
        padding-left: 30px;
      }
    }
  }
}
</style>